<?php
/**
 * DYSHOP
 * ============================================================================
 * 版权所有 2005-2028 杭州鼎易信息科技有限公司，并保留所有权利。
 * 网站地址: https://www.doing.net.cn
 * ==========================================
 * 本系统由鼎易科技团队开发 156791994@qq.com
 * ============================================================================
 * $Author: TANGYIN 2020-06-06 $
 *
 */

namespace app\admin\controller;
use think\facade\View;

use think\facade\Db;
use think\facade\Cache;


class WeChat extends Base
{
    public function weChatUrl(){
        $param = input("param.");
        $WeChatUrl = $param['WeChatUrl'];
//        $WeChatUrl = 'https://mp.weixin.qq.com/s/d4zCma5uotKArgEkP-63NQ';
//        $WeChatUrl = 'https://mp.weixin.qq.com/s/XK-qjn4N4KqsH3N6maIeaQ';
//        set_time_limit(5*60);
//        ini_set("memory_limit", "1024M");
        $title = $content = $coverimg = $vid = $video_url = $background_pic = $background_img = $str = $str1 = '';
        $matchs = $js_content = array();
        $num = $video_type = 0;
        //return dyajaxReturn(0,'请输入要采集的微信网址',$param);
        if(empty($WeChatUrl)){
            return dyajaxReturn(0,'请输入要采集的微信网址');
        }
        if(strstr($WeChatUrl,"https://mp.weixin.qq.com") === false){
            return dyajaxReturn(0,'请输入要采集的微信网址!');
        }

        //$html = @file_get_contents($WeChatUrl);
        $html = curlGet($WeChatUrl);

        preg_match_all("/id=\"js_content\" style=\"visibility: hidden;\">(.*?)<\/div>/is",$html,$js_content,PREG_PATTERN_ORDER);
        //文章内容
        if(isset($js_content[1][0])){
            $content = "<div id='js_content'>".$js_content[1][0]."</div>";
            $content = str_replace("data-src","src",$content);
        }
        //文章封面地址
        preg_match_all('/var msg_cdn_url = \"(.*?)\";/si',$html,$matchs);
        if(isset($matchs[1][0])){
            $cover = $matchs[1][0];
        }
        //标题
        preg_match_all('/var msg_title = \'(.*?)\'/si',$html,$matchs);
        if(isset($matchs[1][0])){
            $title = $matchs[1][0];
        }

        //获取iframe中的视频
        preg_match_all("/<iframe(.*?)><\/iframe>/i",$content,$matchs);
        $iframe = @$matchs[0];
        $iframe_arr = $new_iframe_arr = [];

        $videoPageInfos = "";
        if($iframe){
            //图文视频相关数据 videoPageInfos
            preg_match_all('/var videoPageInfos =(.*?)window.__videoPageInfos/si',$html,$matchs);
            if(isset($matchs[1][0])){
                $videoPageInfos = $matchs[1][0];
            }
            //dyajaxReturn(1,'2324!',$videoPageInfos);
            foreach($iframe as $fv){
                preg_match('/data-vidtype="(.*?)"/', $fv, $matchs);

                $video_type = $matchs[1];//视频类型
                $iframe_arr['name'] = 'iframe_video';
                $iframe_arr['video_type'] = $video_type;
                switch($video_type){
                    case 1:
                        //腾讯视频自带播放器
                        preg_match('/iframe(.*?) src="([^"]+)"/', $fv, $matchs);
                        $vurl = $matchs[2]?explode('vid=',$matchs[2]):'';
                        $vid = $vurl?explode('&',$vurl[1])[0]:'';
                        $iframe_arr['vid'] = $vid;
                        $iframe_arr['background_pic'] = '';
                        $iframe_arr['background_img'] = '';
                        break;
                    case 2:
                        //video标签
                        //获取视频背景图
                        preg_match('/data-cover="(.*?)"/', $fv, $matchs);
                        $_background_img_a = $matchs[1]?urldecode($matchs[1]):'';
                        if($_background_img_a){
                            $_background_img = str_replace('?wx_fmt=','.',$_background_img_a);
                            $_background_img = $this->saveImage($_background_img);
                            $background_pic  = $_background_img['save_path'];
                            $background_img  = $_background_img['file_name'];
                        }
                        preg_match('/data-mpvid="(.*?)"/', $fv, $matchs);
                        $vid = $matchs[1]?$matchs[1]:'';
                        $iframe_arr['vid'] = $vid;
                        $iframe_arr['background_pic'] = $background_pic;
                        $iframe_arr['background_img'] = $background_img;
                        break;
                }
                $iframe_arr['iframe'] = $fv;
                $new_iframe_arr[] = $iframe_arr;
            }
        }
        //dyajaxReturn(1,'2324!',$new_iframe_arr);
        //全局替换视频
        if($new_iframe_arr){
            foreach($new_iframe_arr as $nf){
                switch($nf['video_type']){
                    case 1:
                        //腾讯视频自带播放器
                        $videostr = '<iframe frameborder="0" width="99%" height="99%" src="https://v.qq.com/txp/iframe/player.html?vid='.$nf['vid'].'" allowFullScreen="true"></iframe>';
                        break;
                    case 2:
                        //video标签
                        $video_html = substr($videoPageInfos,stripos($videoPageInfos ,$nf['vid']));
                        $video_html = substr($video_html,stripos($video_html ,"cover_url")+9);
                        $video_html = substr($video_html,stripos($video_html ,"video_quality_level")+1);
                        $video_html = substr($video_html,stripos($video_html ,"video_quality_level")+1);
                        $video_html = substr($video_html,0,stripos($video_html ,"video_quality_level"));
                        $video_html = substr($video_html,stripos($video_html ,"url: (")+5);
                        preg_match_all('/\'(.*?)\'/si',$video_html,$matchs);
                        if(isset($matchs[1][0])){
                            $video_url = $matchs[1][0];
                            $video_url = str_replace('\x26amp;','&',$video_url);
                        }
                        $video_url = "https://www.15um.com/tools/wxvideo_dw.php?url=".urlencode($video_url)."&name=".time().".mp4";
                        //$video_json = 'https://mp.weixin.qq.com/mp/videoplayer?action=get_mp_video_play_url&vid='.$nf['vid'];
                        //$json_arr = json_decode(file_get_contents($video_json),true);
                        //$json_arr = json_decode(http_url($video_json),true);
                        //$video_url = $json_arr['url_info'][1]['url'];
                        //dyajaxReturn(1,'2324!',$video_url);
                        $video_url = $this->downloadTest($video_url);
                        $video_url_path = $video_url['save_path'];
                        $videostr = '<video controls="" loop="loop" name="media" width="99%" height="99%" controlslist="nodownload" poster="'.$nf['background_pic'].'"><source src="'.$video_url_path.'" type="video/mp4"></video>';
                        break;
                }
                $content = str_replace($nf['iframe'], $videostr, $content);
            }
        }

        if(trim($content) == "<p id='js_content'>" || empty($title) || empty($content)) dyajaxReturn(0,'可能是链接已过期，采集失败');

        //此处需要做特殊处理
        preg_match("/croporisrc=\"(.*?)\"/i",$content,$match);
        if($match) $content = str_replace($match[0],'',$content);

        header('Content-Type:text/html; charset=utf-8');
        $imgarr = $this->getImgs($content);
        $bgimgarr = $this->getbgImgs($content);
        $bgimgarr2 = $this->getbgImgs2($content);
        $imgarr = $imgarr ? $imgarr : array();
        $bgimgarr = $bgimgarr ? $bgimgarr : array();
        $bgimgarr2 = $bgimgarr2 ? $bgimgarr2 : array();
        $imgarr = array_merge($imgarr,$bgimgarr);
        $imgarr = array_merge($imgarr,$bgimgarr2);
        /* if($pathfiles){
            foreach ($pathfiles as $file) {
                if (is_file($file)) {
                    @unlink($file);
                }
            }
        } */

        if($imgarr){
            foreach($imgarr as $k=>$v){
                if(strpos($v,'?wx_fmt=') === false){
                    if(strpos($v,'mmbiz_') === false){
                        $img = str_replace('?','',$v).'.jpg';
                    }else{
                        $img_str = str_replace('https://mmbiz.qpic.cn/','',$v);
                        $fm = str_replace('mmbiz_','',explode('/',$img_str)[0]);
                        $img = $v.'.'.$fm;
                    }
                }else{
                    $subimg = substr($v,stripos($v ,'?wx_fmt=')+8);
                    if(strpos($subimg,'&') === false){
                        $img = str_replace('?wx_fmt=','.',$v);
                    }else{
                        $extimg = substr($subimg,0,stripos($subimg,"&"));
                        $img = str_replace('?wx_fmt=','.',$v);
                        $img = str_replace($subimg,$extimg,$img);
                    }
                }
                $str .= $this->saveImage($img)['save_path'].',';
                sleep(0.3);
                $str1 .= $v.',';
                $num += 1;
            }
        }

        $str = explode(',',rtrim($str,','));
        $str1 = explode(',',rtrim($str1,','));
        $newarr = [];
        foreach($str as $key=>$val){
            $arr['imga'] = $val;
            $arr['imgb'] = $str1[$key];
            $newarr[] = $arr;
        }
        foreach($newarr as $pic){
            $content = str_replace($pic['imgb'],$pic['imga'],$content);
        }
        $coverimg = "";
         if($cover){
            $_coverimg = str_replace('?wx_fmt=','.',$cover);
            $_coverimg = $this->saveImage($_coverimg);
            $coverpic = $_coverimg['save_path'];
            $coverimg = $_coverimg['file_name'];

            $cove_url = $coverpic;
            $num += 1;
        }

        $data = array('title'=>$title, 'cover'=>$cove_url, 'picnum'=>$num, 'content'=>$content);
        dyajaxReturn(1,'采集成功',$data);

        //dyajaxReturn(1,'2324!',$content);

    }


    //获取内容中的所有图片
    public function getImgs($content,$order='ALL'){
        $pattern="/<img.*? src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
        preg_match_all($pattern,$content,$matchs);
        if(isset($matchs[1])&&!empty($matchs[1])){
            if($order==='ALL'){
                return $matchs[1];
            }
            if(is_numeric($order)&&isset($matchs[1][$order])){
                return $matchs[1][$order];
            }
        }
        return '';
    }

    //获取内容中的所有背景图片
    public function getbgImgs($content,$order='ALL'){
        $pattern = "/background-image: url\([\'|\"](.*?)[\'|\"]/";//匹配背景的url的正则表达式

        $content = str_replace('&quot;','"',$content);
        preg_match_all($pattern, $content, $matchs);//这里匹配所有的背景img
        if(isset($matchs[1])&&!empty($matchs[1])){
            if($order==='ALL'){
                return $matchs[1];
            }
            if(is_numeric($order)&&isset($matchs[1][$order])){
                return $matchs[1][$order];
            }
        }

        return '';
    }

    public function getbgImgs2($content,$order='ALL'){
        $pattern = "/background-image: url\((.*?)\)/";//匹配背景的url的正则表达式

        $content = str_replace('&quot;','"',$content);
        preg_match_all($pattern, $content, $matchs);//这里匹配所有的背景img
        if(isset($matchs[1])&&!empty($matchs[1])){
            if($order==='ALL'){
                return $matchs[1];
            }
            if(is_numeric($order)&&isset($matchs[1][$order])){
                return $matchs[1][$order];
            }
        }

        return '';
    }


    //保存图片
    public function saveImage($url, $type = 1){
        if (trim($url) == '') {
            return ['errcode' => 0, 'file_name' => '', 'save_path' => ''];
        }
        //保存文件名
        $ext = strrchr($url, '.');
        if (!in_array($ext, ['.png', '.gif', '.jpeg', '.jpg', '.svg'])) {
            return ['errcode' => 0, 'file_name' => '', 'save_path' => ''];
        }
        //文件命名规则
        $filename = date('ymdhis', time()).rand(10000,99999) . $ext;

        //创建保存目录，不存在时使用默认规则
        $save_dir = './upload/wximg/'.date("Ymd").'/';
        if (!file_exists($save_dir) && !mkdir($save_dir, 0755, true)) {
            return ['errcode' => 0, 'file_name' => '', 'save_path' => ''];
        }

        if ($type) {
            $img = curlGet($url);
        } else {
            ob_start();
            readfile($url);
            $img = ob_get_contents();
            ob_end_clean();
        }
        //文件大小
        $fp2 = @fopen($save_dir . $filename, 'a');
        fwrite($fp2, $img);
        fclose($fp2);
        unset($img, $url);
        return ['errcode' => 0, 'file_name' => $filename, 'save_path' => mb_substr($save_dir . $filename, 1)];
    }


    //下载视频
    /*public function downloadTest($url,$ext='mp4')
    {
        $header = [
//             "Origin: https://mp.weixin.qq.com",
//            "Referer: https://mp.weixin.qq.com/",
            "Origin: ttps://www.15um.com",
            "Referer: ttps://www.15um.com/",
            'sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
            "sec-ch-ua-mobile: ?0",
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
        ];

        set_time_limit(0);//抓取不受时间限制
        $url=str_replace('&amp;','&',$url);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if(!empty($header)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        $values = curl_exec($curl);
        curl_close($curl);
        // 生成唯一视频名称
        $uuid = date('ymdhis', time()).rand(10000,99999);

        // 视频名称+后缀
        $filename = "$uuid.$ext";
        $save_dir = "./upload/wximg/".date("Ymd").'/';
        $path = $save_dir;

        if(!is_dir($path)){
            mkdir($path,'0755',true);
        }

        $fp2 = @fopen($path.$filename,'wb');
        fputs($fp2, $values);
        fclose($fp2);

        return ['errcode' => 0, 'file_name' => $filename, 'save_path' => $save_dir . $filename];
    }*/

    //下载视频
    public function downloadTest($url,$ext='mp4')
    {
        $header = [
            /* "Origin: https://mp.weixin.qq.com",
            "Referer: https://mp.weixin.qq.com/", */
            "Origin: https://www.15um.com",
            "Referer: https://www.15um.com/",
            'sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
            "sec-ch-ua-mobile: ?0",
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
        ];

        set_time_limit(0);//抓取不受时间限制
        $url=str_replace('&amp;','&',$url);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if(!empty($header)){
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_HEADER, 0);//返回response头部信息
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

        $values = curl_exec($curl);
        curl_close($curl);
        // 生成唯一视频名称
        $uuid = date('ymdhis', time()).rand(10000,99999);

        // 视频名称+后缀
        $filename = "$uuid.$ext";
//        $save_dir = "/uploadfile/wximg/".date("Ymd").'/';
//        $path = __ROOT__.$save_dir;
        $save_dir = "./upload/wximg/".date("Ymd").'/';
        $save_dir2 = "/upload/wximg/".date("Ymd").'/';
        $path = $save_dir;

        if(!is_dir($path)){
            mkdir($path,'0755',true);
        }

        $fp2 = @fopen($path.$filename,'wb');
        fputs($fp2, $values);
        fclose($fp2);

        return ['errcode' => 0, 'file_name' => $filename, 'save_path' => $save_dir2 . $filename];
    }

}